#include <Windows.h>
#include <string>
#include "Message.h"
#include "MessageSystem.h"
#include "Subscriber.h"

class StrMessage : public Message
{
	std::string m_message;
	static const int s_message_id = 1;

public:
	StrMessage (std::string someText) : Message(s_message_id)
	{
		m_message = someText;
	}

	const std::string& get_message() const
	{
		return m_message;
	}
};

void publisher( void* ptr )
{
	int ii = 0;
	while(true)
	{
		Sleep(10);
		StrMessage *sMsg = new StrMessage("hello other threads");
		MessageSystem::GetInstance()->publish_message(sMsg);
		++ii;
		if(ii%1000==0)
		{
			ii = 0;
			fprintf(stderr,".");
		}
	}
}
void receiver_1( void* ptr )
{
	// create subscriber and add to msg system
	Subscriber sub;
	sub.add_subscription(1);
	MessageSystem::GetInstance()->add_subscriber(&sub);

	while(true)
	{
		Sleep(500);
		while(sub.has_messages())
		{
			Message *msg = sub.get_message();
			StrMessage *smsg = dynamic_cast<StrMessage*>(msg);
			{
				fprintf(stderr,"Receiver 1 says: %s\n", smsg->get_message().c_str());
			}
			delete msg;
		}
	}
}
void receiver_2( void* ptr )
{
	// create subscriber and add to msg system
	Subscriber sub;
	sub.add_subscription(1);
	MessageSystem::GetInstance()->add_subscriber(&sub);

	while(true)
	{
		Sleep(5000);
		while(sub.has_messages())
		{
			Message *msg = sub.get_message();
			StrMessage *smsg = dynamic_cast<StrMessage*>(msg);
			if(smsg)
			{
				fprintf(stderr,"Receiver 2 says: %s\n", smsg->get_message().c_str());
			}
			delete msg;
		}
	}
}


int main ( )
{
	CreateThread( 0, 0, (LPTHREAD_START_ROUTINE)publisher, 0, 0, 0 );
	CreateThread( 0, 0, (LPTHREAD_START_ROUTINE)receiver_1, 0, 0, 0 );
	CreateThread( 0, 0, (LPTHREAD_START_ROUTINE)receiver_2, 0, 0, 0 );
	while(true)
	{
		Sleep(-1);
	}

	return 0;
}